package cn.shiwei.hr.config;

import cn.shiwei.hr.handler.MyAuthenticationFailureHandler;
import cn.shiwei.hr.handler.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
// 开启Security
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //配置认证管理器，授权模式为“password”时会用到
    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }



    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()                                //授权配置
                .antMatchers("/login/userLogin", "/login/entering").permitAll()  //登录路径放行
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                .successHandler(new MyAuthenticationSuccessHandler()) // 设置登录成功返回信息
                .failureHandler(new MyAuthenticationFailureHandler()) // 设置登录失败
                .and().logout().permitAll()                    //登出路径放行
                .and().csrf().disable();                        //关闭跨域伪造检查


        //异常处理
//        http.exceptionHandling()
//                .accessDeniedHandler(new DefaultAccessDeniedHandler ()) // 没有权限, 认证失败
//                .authenticationEntryPoint(new DefaultAccessDeniedHandler()); // 匿名用户没有权限

    }


}
